//
//  PersonCenterController.m
//  easystudy
//
//  Created by kane on 15/6/1.
//  Copyright (c) 2015年 kane. All rights reserved.
//

#import "PersonCenterController.h"

#import "FeedBackController.h"
#import "AboutViewController.h"
#import "LDAboutSetViewController.h"
#import "LoginAndRegistController.h"
#import "FavoriteListController.h"
#import "PersonInfoController.h"
#import "MyMessageController.h"
#import "MyCollectController.h"
#import "NewsPushController.h"
#import "SetViewController.h"
#import "WebViewController.h"

#import "ASProgressPopUpView.h"
@interface PersonCenterController ()<UIScrollViewDelegate,UITableViewDelegate,UITableViewDataSource>
{
    __weak IBOutlet UIImageView *topImageView;
    __weak IBOutlet UIButton *photoBtn;
    __weak IBOutlet UILabel *nameLbl;
    __weak IBOutlet UITableView *bottomTable;
    __weak IBOutlet UIButton *myMedieBtn;
    
    
    __weak IBOutlet UIView *topView;
    int i;
    ASProgressPopUpView *progressView;
    UILabel *downloadPerLbl;
    UILabel *percentLbl;
    int isDownload;
}

@end

@implementation PersonCenterController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [photoBtn drawCornerRadius:photoBtn.width/2];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeNightMode) name:kChangeNightMode object:nil];
    self.automaticallyAdjustsScrollViewInsets = NO;//解决IOS 7.0以上TableView上面会有20像素的空白（无法遮挡状态栏）
    [self changeNightMode];
    isDownload = 1;
    progressView = [[ASProgressPopUpView alloc]init];
    downloadPerLbl = [[UILabel alloc] init];
    percentLbl = [[UILabel alloc] init];
    i=0;
    [myMedieBtn setHidden:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:NotificationLoginSuccess object:nil];
}

- (void)changeNick
{
    [bottomTable reloadData];
    nameLbl.text = [UserEntity sharedUser].NickName;
}

-(void)loginSuccess:(NSNotification *)notify
{
    [myMedieBtn setHidden:NO];
    [myMedieBtn.layer setMasksToBounds:NO];
    myMedieBtn.layer.cornerRadius = 10.0;
    myMedieBtn.layer.borderColor = [UIColor whiteColor].CGColor;
    myMedieBtn.layer.borderWidth = 1.0;
    [myMedieBtn addTarget:self action:@selector(myMediaBtnPress) forControlEvents:UIControlEventTouchUpInside];
}

- (void)changeNightMode
{
    topView.backgroundColor = KKColor_DarkWhite_Black;
    bottomTable.backgroundColor = KKColor_DarkWhite_Black;
    
    [bottomTable reloadData];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    [super viewWillAppear:animated];
    [self initUI];
}

- (void)initUI
{
    myMedieBtn.hidden = ![UserEntity sharedUser].loginSuccess;
    if ([UserEntity sharedUser].loginSuccess) {
        if ([UserEntity sharedUser].NickName.length<=0) {
            [UserEntity sharedUser].NickName = @"司徒博仁";
        }
        nameLbl.text = [UserEntity sharedUser].NickName;
        NSString *url = @"";
        if ([UserEntity sharedUser].PictureUrl.length > 0) {
            url = [NSString stringWithFormat:@"%@%@",FileURL,[UserEntity sharedUser].PictureUrl];
        }
        [photoBtn setImageForState:UIControlStateNormal withURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@"person_icon"]];
    }else{
        nameLbl.text = @"未登录";
        [photoBtn setImage:[UIImage imageNamed:@"person_icon"] forState:UIControlStateNormal];
    }
}


#pragma mark - User Actions
//自媒体
- (IBAction)selfBtnPressed:(id)sender
{

}

//个人信息
- (IBAction)photoBtnPressed:(id)sender
{
    if ([UserEntity sharedUser].loginSuccess) {
        PersonInfoController *infoVC = [[PersonInfoController alloc] init];
        infoVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:infoVC animated:YES];
    }else{
        //登录页面
        LoginAndRegistController *loginVC = [[LoginAndRegistController alloc] init];
        loginVC.isFromSetView = NO;
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:YES];
    }
}

- (void)switchChanged:(UISwitch *)sender
{
    [[NSUserDefaults standardUserDefaults] setObject:@(sender.on) forKey:@"NightMode"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if (sender.on) {
        [[UIScreen mainScreen] setBrightness:0.2];
    }else{
        [[UIScreen mainScreen] setBrightness:0.4];
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:kChangeNightMode object:nil];
    [bottomTable reloadData];
}

- (void) myMediaBtnPress{//自媒体
    WebViewController *webVC = [[WebViewController alloc] init];
    webVC.urlString = @"http://mp.yidianzixun.com/";
    webVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark UITableViewDelegate & datasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identify = [NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
        if (indexPath.section == 1 && indexPath.row == 0) {
            UISwitch *nightSwith = [[UISwitch alloc] initWithFrame:CGRectZero];
            [nightSwith setOn:IS_NightMode];
            cell.accessoryView = nightSwith;
            [nightSwith addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
        }else{
            [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
        }
    }
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.textLabel.textColor = KKColor_Black_LightGary;
    cell.backgroundColor = KKColor_DarkGray_White;
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row == 0) {
                cell.imageView.image = [UIImage imageNamed:@"personal_message"];
                cell.textLabel.text = @"我的消息";
            }else if(indexPath.row == 1){
                cell.imageView.image = [UIImage imageNamed:@"personal_collect"];
                cell.textLabel.text = @"我的收藏";
            }else{
                cell.imageView.image = [UIImage imageNamed:@"personal_push"];
                cell.textLabel.text = @"新闻推送";
            }
    }break;
        default:
            if (indexPath.row == 0) {
                cell.imageView.image = [UIImage imageNamed:@"personal_night"];
                cell.textLabel.text = @"夜间模式";
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }else if(indexPath.row == 1){
                cell.imageView.image = [UIImage imageNamed:@"personal_download"];
                if (isDownload %2 == 0) {
                    progressView.frame = CGRectMake(140, 22, 100, 5);
                    downloadPerLbl.frame = CGRectMake(250, 0, 40, 44 );
                    downloadPerLbl.font = [UIFont systemFontOfSize:12];
                    downloadPerLbl.textColor = [UIColor colorWithHex:0X46C09A];
                    [cell addSubview:downloadPerLbl];
                    cell.textLabel.text = @"取消下载";
                    [cell addSubview:progressView];
                    [cell addSubview:percentLbl];
                    [cell setAccessoryType:UITableViewCellAccessoryNone];
                }else{
                    cell.textLabel.text = @"离线下载";
                    [progressView removeFromSuperview];
                    [downloadPerLbl removeFromSuperview];
                    [percentLbl removeFromSuperview];
                    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
                }
            }else{
                cell.imageView.image = [UIImage imageNamed:@"personal_set"];
                cell.textLabel.text = @"设置";
            }
            break;
    }
    
    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row == 0) {
                MyMessageController *messVC = [[MyMessageController alloc] init];
                messVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:messVC animated:YES];
            }else if(indexPath.row == 1){
                MyCollectController *collectVC = [[MyCollectController alloc] init];
                collectVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:collectVC animated:YES];
            }else{
                NewsPushController *newsVC = [[NewsPushController alloc] init];
                newsVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:newsVC animated:YES];
            }
            break;
        }
        default:{
            if (indexPath.row == 1) {
                [self progress];
                isDownload +=1;
                [bottomTable reloadData];
                if (isDownload%2==1) {
                    i=0;
                    progressView.progress = 0.0;
                    [self.view makeToast:@"已取消离线下载" position:@"center"];
                }
            }else if(indexPath.row == 2) {
                SetViewController *setVC = [[SetViewController alloc] init];
                setVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:setVC animated:YES];
            }
        }
            break;
    }
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    if ([UserEntity sharedUser].loginSuccess) {
        for (int i = 0; i < 4; i++) {
            UIView *headerContentView = bottomTable.tableHeaderView.subviews[i];
            headerContentView.transform = CGAffineTransformMakeTranslation(0, MIN(offsetY, 0));
        }
    }else{
        for (int i = 0; i < 3; i++) {
            UIView *headerContentView = bottomTable.tableHeaderView.subviews[i];
            headerContentView.transform = CGAffineTransformMakeTranslation(0, MIN(offsetY, 0));
        }
    }
    
}


#pragma mark - Timer

- (void)progress
{
    if (progressView.progress >= 1.0) {
        
    }if (i<100) {
        i+=1;
    }
    
    downloadPerLbl.text = [[NSString stringWithFormat:@"%d",i] stringByAppendingString:@"%"];
    float progress = progressView.progress;
    if (progress < 1.0) {
        
        progress += 0.01;
        
        [progressView setProgress:progress animated:YES];
        
        [NSTimer scheduledTimerWithTimeInterval:0.5
                                         target:self
                                       selector:@selector(progress)
                                       userInfo:nil
                                        repeats:NO];
    }
}

#pragma mark - ASProgressPopUpView dataSource

// <ASProgressPopUpViewDataSource> is entirely optional
// it allows you to supply custom NSStrings to ASProgressPopUpView
- (NSString *)progressView:(ASProgressPopUpView *)progressView stringForProgress:(float)progress
{
    NSString *s;
    if (progress < 0.2) {
        s = @"Just starting";
    } else if (progress > 0.4 && progress < 0.6) {
        s = @"About halfway";
    } else if (progress > 0.75 && progress < 1.0) {
        s = @"Nearly there";
    } else if (progress >= 1.0) {
        s = @"Complete";
    }
    return s;
}

// by default ASProgressPopUpView precalculates the largest popUpView size needed
// it then uses this size for all values and maintains a consistent size
// if you want the popUpView size to adapt as values change then return 'NO'
- (BOOL)progressViewShouldPreCalculatePopUpViewSize:(ASProgressPopUpView *)progressView;
{
    return NO;
}




@end
